/**
 * 对话导出组件
 */

import React, { useState } from 'react';
import { chatHistoryService } from '../services/chatHistoryService';
import './ChatExport.css';

interface ChatExportProps {
    onClose: () => void;
}

const ChatExport: React.FC<ChatExportProps> = ({ onClose }) => {
    const [isExporting, setIsExporting] = useState(false);
    const [exportFormat, setExportFormat] = useState<'text' | 'json'>('text');

    // 导出对话历史
    const handleExport = async () => {
        setIsExporting(true);

        try {
            let content: string;
            let filename: string;
            let mimeType: string;

            if (exportFormat === 'text') {
                content = chatHistoryService.exportAsText();
                filename = `对话历史_${new Date().toISOString().split('T')[0]}.txt`;
                mimeType = 'text/plain;charset=utf-8';
            } else {
                content = chatHistoryService.exportAsJson();
                filename = `对话历史_${new Date().toISOString().split('T')[0]}.json`;
                mimeType = 'application/json;charset=utf-8';
            }

            // 创建Blob并下载
            const blob = new Blob([content], { type: mimeType });
            const url = URL.createObjectURL(blob);

            const link = document.createElement('a');
            link.href = url;
            link.download = filename;
            document.body.appendChild(link);
            link.click();
            document.body.removeChild(link);

            URL.revokeObjectURL(url);

            console.log('✅ 对话历史导出成功:', filename);

        } catch (error) {
            console.error('❌ 导出失败:', error);
            alert('导出失败，请重试');
        } finally {
            setIsExporting(false);
        }
    };

    // 获取统计信息
    const getStats = () => {
        const messages = chatHistoryService.getAllMessages();
        const sessions = chatHistoryService.getAllSessions();
        const currentSession = chatHistoryService.getCurrentSession();

        return {
            totalMessages: messages.length,
            totalSessions: sessions.length,
            currentSessionMessages: currentSession?.messages.length || 0,
            userMessages: messages.filter(m => m.type === 'user').length,
            aiMessages: messages.filter(m => m.type === 'ai').length
        };
    };

    const stats = getStats();

    return (
        <div className="chat-export-overlay">
            <div className="chat-export-panel">
                <div className="chat-export-header">
                    <h3>📤 导出对话历史</h3>
                    <button className="chat-export-close" onClick={onClose}>
                        ✕
                    </button>
                </div>

                <div className="chat-export-content">
                    {/* 统计信息 */}
                    <div className="chat-export-stats">
                        <h4>📊 对话统计</h4>
                        <div className="stats-grid">
                            <div className="stat-item">
                                <span className="stat-label">总会话数:</span>
                                <span className="stat-value">{stats.totalSessions}</span>
                            </div>
                            <div className="stat-item">
                                <span className="stat-label">总消息数:</span>
                                <span className="stat-value">{stats.totalMessages}</span>
                            </div>
                            <div className="stat-item">
                                <span className="stat-label">用户消息:</span>
                                <span className="stat-value">{stats.userMessages}</span>
                            </div>
                            <div className="stat-item">
                                <span className="stat-label">AI回复:</span>
                                <span className="stat-value">{stats.aiMessages}</span>
                            </div>
                            <div className="stat-item">
                                <span className="stat-label">当前会话:</span>
                                <span className="stat-value">{stats.currentSessionMessages} 条消息</span>
                            </div>
                        </div>
                    </div>

                    {/* 导出格式选择 */}
                    <div className="chat-export-format">
                        <h4>📄 导出格式</h4>
                        <div className="format-options">
                            <label className="format-option">
                                <input
                                    type="radio"
                                    name="format"
                                    value="text"
                                    checked={exportFormat === 'text'}
                                    onChange={(e) => setExportFormat(e.target.value as 'text' | 'json')}
                                />
                                <span>📝 文本格式 (.txt)</span>
                                <small>适合阅读，包含时间戳和会话信息</small>
                            </label>
                            <label className="format-option">
                                <input
                                    type="radio"
                                    name="format"
                                    value="json"
                                    checked={exportFormat === 'json'}
                                    onChange={(e) => setExportFormat(e.target.value as 'text' | 'json')}
                                />
                                <span>🔧 JSON格式 (.json)</span>
                                <small>结构化数据，适合程序处理</small>
                            </label>
                        </div>
                    </div>

                    {/* 导出按钮 */}
                    <div className="chat-export-actions">
                        <button
                            className="chat-export-btn"
                            onClick={handleExport}
                            disabled={isExporting || stats.totalMessages === 0}
                        >
                            {isExporting ? '⏳ 导出中...' : '📤 导出对话历史'}
                        </button>

                        {stats.totalMessages === 0 && (
                            <p className="no-data-message">
                                📭 暂无对话记录，请先与AI对话后再导出
                            </p>
                        )}
                    </div>
                </div>
            </div>
        </div>
    );
};

export default ChatExport;
